package com.zynn.common.core.utils;

import com.zynn.common.core.constant.QiNiuConstant;
import com.zynn.common.core.constant.YinianConstant;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

/**
 * 二维码 海报生产工具类
 *
 * @author 杨岳
 * @date 2018/7/5 13:58
 */
@Slf4j
public class PosterUtils {

    /**
     * 获取二维码   并且上传到 七牛云公有云
     *
     * @param url      生成二维码的访问路径
     * @param param    二维码携带的参数
     * @param fileName 二维码存放空间的名字
     * @param type     上传到什么空间         public 公开云   private 私有云
     * @return
     */
    public static byte[] getQRcode(String url, String param, String fileName, String type) {
        PrintWriter out = null;
        BufferedInputStream input = null;
        byte[] unitByte = new byte[0];
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取输入流并获取图片
            input = new BufferedInputStream(conn.getInputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = input.read(data)) != -1) {
                unitByte = Arrays.copyOf(unitByte, unitByte.length + len);
                System.arraycopy(data, 0, unitByte, unitByte.length - len, len);
            }
            String s = new String(unitByte);
            System.out.println(s);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！", e);
        }
        //关闭 输入输出流
        finally {
            try {
                out.close();
                input.close();
            } catch (IOException ex) {
                log.error("二维码读取流关闭异常", ex);
            }
        }
        return unitByte;
    }


    /**
     * 剪切图片 为方形
     *
     * @param inputImage
     * @param newWidth
     * @param newHeight
     * @return
     * @throws Exception
     */
    public static BufferedImage scaleByPercentage(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
        // 获取原始图像透明度类型
        int type = inputImage.getColorModel().getTransparency();
        int width = inputImage.getWidth();
        int height = inputImage.getHeight();
        // 开启抗锯齿
        RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 使用高质量压缩
        renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        BufferedImage img = new BufferedImage(newWidth, newHeight, type);
        Graphics2D graphics2d = img.createGraphics();
        graphics2d.setRenderingHints(renderingHints);
        graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
        graphics2d.dispose();
        return img;
    }

    /**
     * 传入的图像必须是正方形的 才会 圆形 如果是长方形的比例则会变成椭圆的
     *
     * @param bi1 用户头像地址
     * @return
     * @throws IOException
     */
    public static BufferedImage convertCircular(BufferedImage bi1) throws IOException {
        // 透明底的图片
        BufferedImage bi2 = new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1, 0, 0, null);
        // 设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }

    /**
     * @param gs
     * @param width       底图的宽度
     * @param height
     * @param showContent
     * @param size
     */
    public static void insertTextFor(Graphics2D gs, int width, int height, String userName, String showContent, int size) {
        gs.setColor(new Color(255, 255, 255));
        Font font = new Font(null, Font.TRUETYPE_FONT, size);
        FontMetrics metrics = gs.getFontMetrics(font);
        //设置字体
        gs.setFont(font);
        int s1Len = metrics.stringWidth(userName + showContent);
        if (s1Len > width * 0.8) {
            int nameLen = metrics.stringWidth(userName);
            int startX = (width - nameLen) / 2;
            //画字符串
            gs.drawString(userName, startX, height);
            int contentLen = metrics.stringWidth(showContent);
            gs.drawString(showContent, (width - contentLen) / 2, height + 50);
        } else {
            int startX = (width - s1Len) / 2;
            //画字符串
            gs.drawString(userName + showContent, startX, height);
        }
    }

    /**
     * * 生产二维码 并保存到七牛云 返回路径* 生产二维码 并保存到七牛云 返回路径
     *
     * @param url      跳转路径
     * @param param    参数
     * @param fileName 保存的文件名称
     * @param type     公开云还是私有云
     * @return 二维码图地址
     */
    public static String getQRcodeToQiniu(String url, String param, String fileName, String type) {
        PrintWriter out = null;
        BufferedInputStream input = null;
        byte[] unitByte = new byte[0];
        byte[] restlt;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取输入流并获取图片
            input = new BufferedInputStream(conn.getInputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = input.read(data)) != -1) {
                unitByte = Arrays.copyOf(unitByte, unitByte.length + len);
                System.arraycopy(data, 0, unitByte, unitByte.length - len, len);
            }
            System.out.println( new String(data,"utf-8"));
            if (YinianConstant.PUBLIC.equals(type)) {
                QiniuOperateUtil.uploadByteToOpenSpace(unitByte, fileName);
            } else if (YinianConstant.PRIVATE.equals(type)) {
                QiniuOperateUtil.uploadByteToPrivateSpace(unitByte, fileName);
            }
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！", e);
        }
        //关闭 输入输出流
        finally {
            try {
                assert out != null;
                out.close();
                assert input != null;
                input.close();
            } catch (IOException ex) {
                log.error("二维码读取流关闭异常", ex);
            }
        }
        if (YinianConstant.PUBLIC.equals(type)) {
            QiniuOperateUtil.uploadByteToOpenSpace(unitByte, fileName);
            return QiNiuConstant.QI_NIU_OPEN_ADDRESS + fileName;
        }
        return QiNiuConstant.QI_NIU_PRIVATE_ADDRESS + fileName;
    }
}
